const { desktopCapturer, shell, ipcRenderer } = require("electron");
const path = require("path");
const fs = require('fs');

let mediaRecorder = null;

let chunks = [];

async function start() {
    console.log('触发了');
    if (mediaRecorder) return;

    const sources = await desktopCapturer.getSources({ types: ["screen"] });
    // webRtc领域的API 提示用户给与使用媒体输入的许可 有点东西
    // 返回一个promise对象
    const stream = await navigator.mediaDevices.getUserMedia({
        audio: false,
        video: {
            mandatory: {
                chromeMediaSource: "screen",
                chromeMediaSourceId: sources[0].id,
            },
        },
    })
    mediaRecorder = new MediaRecorder(stream, { mimeType: "video/webm; codecs=vp9" });
    // 获取数据流压入栈中
    mediaRecorder.ondataavailable = (event) => {
        event.data.size > 0 && chunks.push(event.data);
    };

    mediaRecorder.start();
    console.log(mediaRecorder.state,'检测状态开始')
    updateStatusText('录制中...')
}

function stop(downLoadPath) {
    if (!mediaRecorder) return
    console.log(mediaRecorder.state,'检测状态关闭')
    mediaRecorder.onstop = async () => {
        const blob = new Blob(chunks, { type: "video/webm" });
        const buffer = Buffer.from(await blob.arrayBuffer());
        const filePth = path.resolve(downLoadPath, `${Date.now()}.webm`)
        fs.writeFile(filePth, buffer, () => {
            shell.openPath(filePth);
            mediaRecorder = null;
            chunks = [];
        })
    }
    mediaRecorder.stop();
    updateStatusText('空闲')
}

function updateStatusText(text) {
    const $statusElement = document.querySelector("#status");
    $statusElement.textContent = text;
}

export function openRecord() {
    ipcRenderer.on("StartRecording", start);
    ipcRenderer.on("StopRecording", (event,path)=>{
        console.log(path,'送来的路径')
        stop(path)
    });
}